본문으로 건너뛰기

합성 컴포넌트

  • 합성 컴포넌트 : 하나의 컴포넌트를 여러 가지 집합체로 분리한 뒤, 분리된 각 컴포넌트를 사용하는 쪽에서 조합해 사용하는 컴포넌트 패턴
  • 장점 : 재사용성을 극대화 & 직관적

1. 서브 컴포넌트 구현

interface DialogTitleProps {
children?: ReactNode;
}
function DialogTitle({children}: DialogTitleProps){
return <div css={/*DialogTitle 스타일*/}>{children}</div>
}

interface DialogLabelButtonProps {
children?: ReactNode;
onClick?: (e: MouseEvent) => void;
}
function DialogLabelButton({children}: DialogLabelButtonProps){
return <div css={/*DialogLabelButton 스타일*/}>{children}</div>
}

// ... 기타 Dialog 서브 컴포넌트
  • 각 서브 컴포넌트(DialogTitle, DialogLabelButton)

2. 메인 컴포넌트 구현

interface DialogMainProps {
children?: ReactNode;
isOpen: boolean;
}
function DialogMain({children, isOpen}: DialogMainProps){
if(!isOpen) {
return null;
}
return createPortal(<div>{children}</div>, document.body)
}
  • 서브 컴포넌트들을 묶어서 화면에 적절하게 보이도록 하는 Wrapper 성격의 컴포넌트
  • children을 props로 받음

3. 메인 & 서브 컴포넌트를 묶어서 export

// export
export const Dialog = Object.assign(DialogMain, {
Dimmed: DialogDimmed,
Title: DialogTitle,
Subtitle: DialogSubtitle,
Description: DialogDescription,
Comment: DialogComment,
CheckButton: DialogCheckButton,
CheckBox: DialogCheckBox,
TextButton: DialogTextButton,
Button: DialogButton,
LabelButton: DialogLabelButton,
Divider: DialogDivider,
});

// Usage
<Dialog>
<Dialog.Title>제목</Dialog.Title>
</Dialog>

Reference